package com.quanyan.club.sms;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.quanyan.api.APIResponse;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by yue.yuan on 2017/2/17.
 */
@RestController
@RequestMapping(value = "/api/club/sms/")
public class ClubSmsController {

    @Autowired
    private ClubSmsService clubSmsService;

    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    public APIResponse sendSmsCode(@RequestBody Map<String, Object> map) {
        String mobile = MapUtils.getString(map, "mobile");
        if(StringUtils.isBlank(mobile)) {
            return APIResponse.returnFail("手机号为空");
        }
        if(!mobile.matches("^\\d{11}|\\d{13}$")) {
            return APIResponse.returnFail("手机号不合法，请填写11位数字");
        }
        APIResponse apiResponse= clubSmsService.sendSms(mobile);
        if (!apiResponse.isRet() || apiResponse.getErrcode() != 200){
            return APIResponse.returnFail("短信验证码发送失败");
        }
        return APIResponse.returnSuccess("短信验证码发送成功");
    }

    @RequestMapping(value = "checkCode", method = RequestMethod.POST)
    public APIResponse checkSmsCode(@RequestBody Map<String, Object> map) {
        String mobile = MapUtils.getString(map, "mobile");
        String smsCode = MapUtils.getString(map, "smsCode");
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(mobile)) {
            return APIResponse.returnFail("参数不能为空");
        }
        APIResponse apiResponse= clubSmsService.checkCode(smsCode,mobile);
        if (!apiResponse.isRet() || apiResponse.getErrcode() != 200) {
            return APIResponse.returnFail("短信验证码验证失败");
        }
        return APIResponse.returnSuccess("短信验证码验证成功");
    }

}
